package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 超时取消订单 消息消费者
 */
@Component
@Log4j2
public class CancelOrderListener {
    @Resource
    OrderInfoService orderInfoService;
    @RabbitListener(queues = "order_nomal_queue")
    public void orderTimeOut(Message message , Channel channel){
        //获取消息内容
        byte[] body = message.getBody();
        //将消息内容 订单Id 转化为原类型类型
        Long orderId =Long.parseLong( new String(body));
        //获得消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获得消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            //取消订单
            orderInfoService.cancelOrder(orderId);
            //手动确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                //判断消息是不是第二次被消费
                if (messageProperties.getRedelivered()){
                    e.printStackTrace();
                    //第二次消费消息失败将消息存到日志，然后丢弃不放回队列
                    log.error("超时取消订单失败,订单的id为: " + orderId);
                    channel.basicReject(deliveryTag,false);
                }else {
                    //消息第一次被消费 不丢弃放回队列再重试一次
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e1){
                log.error("超时取消订单拒绝消息失败, 失败的订单id为:" + orderId + ",失败的原因为:" + e1.getMessage());
            }
        }


    }
}
